import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { DelonFormModule, SFRadioWidgetSchema, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { Api } from 'src/app/shared/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [NzSpinModule, NzFormModule, DelonFormModule, NzButtonModule]
})
export class UserEditComponent implements OnInit {
  record: any = {};
  schema: SFSchema = {
    properties: {
      account: {
        type: 'string',
        title: '用户名',
        readOnly: this.record && this.record.id,
        maxLength: 63
      },
      name: {
        type: 'string',
        title: '姓名'
      },
      group: {
        type: 'string',
        title: '组',
        ui: {
          widget: 'select',
          mode: 'tags',
          asyncData: () => this.getAllGroup()
        } as SFSelectWidgetSchema,
        default: null
      },
      role: {
        type: 'string',
        title: '组',
        enum: [
          { label: '用户', value: 'USER' },
          { label: '管理员', value: 'ADMIN' }
        ],
        ui: {
          widget: 'radio',
          styleType: 'button',
          buttonStyle: 'solid'
        } as SFRadioWidgetSchema,
        default: 'USER'
      }
    },
    required: ['account', 'name', 'group']
  };
  ui: SFUISchema = {
    '*': {
      spanLabel: 4,
      spanControl: 20,
      grid: { span: 12 }
    }
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient
  ) {}

  ngOnInit(): void {
    this.getAllGroup();
  }

  getAllGroup(): Observable<any> {
    const groupObservable = this.http.get(`${Api.BaseGroupApi}/all`).pipe(
      catchError(() => {
        return [];
      }),
      map(res => {
        if (res && res.code === ResponseCode.SUCCESS) {
          if (res.data) {
            const data: any[] = [];
            res.data.forEach((ele: any) => {
              data.push({ label: ele.name, value: ele.id });
            });
            return data;
          }
        }
        return [];
      })
    );
    return groupObservable;
  }

  close() {
    this.modal.destroy();
  }

  save(value: any) {
    if (value.account.length < 4) {
      this.msgSrv.warning('用户名长度必须大于3');
      return;
    }
    if (this.record.id) {
      this.http.put(Api.BaseUserApi, value).subscribe((res: any) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('修改成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('修改失败，未知错误');
        }
      });
    } else {
      this.http.post(Api.BaseUserApi, value).subscribe((res: any) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('保存成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('保存失败，未知错误');
        }
      });
    }
  }
}
